<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket-TCP Proxy Client</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background: #f4f4f9;
        }
        #container {
            width: 90%;
            margin: 20px auto;
            max-width: 800px;
        }
        #messages {
            height: 300px;
            overflow-y: auto;
            background: white;
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 8px;
        }
        .message {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 5px;
        }
        .message.me {
            background-color: #d1ecf1;
            text-align: left;
        }
        .message.system {
            background-color: #e2e3e5;
            text-align: center;
        }
        .message.server {
            background-color: #d4edda;
            text-align: left;
        }
        #input-container {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
        #input-container input,
        #input-container select,
        #input-container button {
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        #input-container button {
            background-color: #007bff;
            color: white;
            cursor: pointer;
        }
        #input-container button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<div id="container">
    <h1>WebSocket-TCP Proxy Client</h1>
    <div id="messages"></div>
    <div id="input-container">
        <input type="number" id="receiver-id" placeholder="请输入接收方ID">
        <input type="text" id="message" placeholder="请输入消息内容">
        <select id="biz-id">
            <option value="1" selected>JLink (1)</option>
            <option value="3">IM 服务 (3)</option>
        </select>
        <button id="send">发送</button>
    </div>
</div>

<script>
    const serverUrl = "ws://127.0.0.1:8080"; // WebSocket 代理服务器地址
    const ws = new WebSocket(serverUrl);

    let userId = null;
    let heartbeatInterval = null;

    ws.onopen = () => {
        console.log("Connected to WebSocket server");

        // **用户登录，自动发送 message_type = 0**
        userId = prompt("请输入您的用户ID:");
        if (userId) {
            sendJsonMessage({
                sender_id: parseInt(userId),
                receiver_id: null,
                biz_id: 1, // 默认 JLink 业务
                message_type: 0, // **登录类型**
                context: "login request"
            });
            displayMessage(`【系统】已登录，用户ID: ${userId}`, "system");

            // 启动心跳包
            startHeartbeat();
        }
    };

    ws.onmessage = (event) => {
        try {
            const data = JSON.parse(event.data);
            console.log("Received:", data);

            if (data.body && typeof data.body.data === "string") {
                displayMessage(`服务器消息: ${data.body.data}`, "server");
            } else {
                displayMessage("收到服务器响应：" + JSON.stringify(data), "server");
            }
        } catch (error) {
            console.error("Error processing received message:", error);
            displayMessage("消息解析失败：" + error.message, "system");
        }
    };

    ws.onerror = (error) => {
        console.error("WebSocket error:", error);
        displayMessage("连接错误", "system");
    };

    ws.onclose = () => {
        console.log("WebSocket connection closed");
        displayMessage("连接已关闭", "system");
        stopHeartbeat();
    };

    document.getElementById("send").addEventListener("click", () => {
        const messageInput = document.getElementById("message");
        const receiverIdInput = document.getElementById("receiver-id");
        const bizIdInput = document.getElementById("biz-id");

        const messageText = messageInput.value.trim();
        const receiverId = receiverIdInput.value.trim();
        const bizId = parseInt(bizIdInput.value, 10);

        if (messageText && receiverId && ws.readyState === WebSocket.OPEN) {
            const message = {
                sender_id: parseInt(userId),
                receiver_id: parseInt(receiverId),
                biz_id: bizId,
                message_type: 3, // **自动设置为 消息推送 (3)**
                context: messageText,
                session_id:17385748497970004// 会话ID
            };

            sendJsonMessage(message);
            displayMessage(`[用户 ${userId}] 发送给 [用户 ${receiverId}] (业务ID ${bizId}, 类型 3) 的消息: ${messageText}`, "me");

            messageInput.value = "";
        } else {
            alert("请输入接收方ID和消息内容！");
        }
    });

    function startHeartbeat() {
        if (heartbeatInterval) return;
        heartbeatInterval = setInterval(() => {
            if (ws.readyState === WebSocket.OPEN) {
                sendJsonMessage({
                    sender_id: parseInt(userId),
                    receiver_id: null,
                    biz_id: 1, // JLink 业务ID
                    message_type: 1, // **自动设置为 心跳包 (1)**
                    context: "heartbeat"
                });
                displayMessage("【系统】已发送心跳包", "system");
            }
        }, 10000);
    }

    function stopHeartbeat() {
        if (heartbeatInterval) {
            clearInterval(heartbeatInterval);
            heartbeatInterval = null;
        }
    }

    function displayMessage(text, type) {
        const messagesDiv = document.getElementById("messages");
        const messageDiv = document.createElement("div");
        messageDiv.className = `message ${type}`;
        messageDiv.textContent = text;
        messagesDiv.appendChild(messageDiv);
        messagesDiv.scrollTop = messagesDiv.scrollHeight;
    }

    function sendJsonMessage(message) {
        if (ws.readyState !== WebSocket.OPEN) {
            console.error("WebSocket connection is not open");
            return;
        }
        ws.send(JSON.stringify(message));
    }
</script>
</body>
</html>
